package com.example.crmweb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.crmweb.entity.Auth;
import com.example.crmweb.mapper.AuthMapper;
import com.example.crmweb.service.AuthService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.crmweb.lang.Result;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author -CRM-
 * @since 2022-03-18
 */
@Service
public class AuthServiceImpl extends ServiceImpl<AuthMapper, Auth> implements AuthService {

    @Resource
    private AuthMapper mapper;

    /**
     * 查看所有开启的权限
     * @return
     */
    @Override
    public List<Auth> batchDescribe() {
        QueryWrapper<Auth> wrapper = new QueryWrapper<>();
        wrapper.eq("status","open");
        return  mapper.selectList(wrapper);
    }

    /**
     * 软删除
     * @param id
     * @return
     */
    @Override
    public Result delete(Integer id) {
        Auth auth = mapper.selectById(id);
        auth.setStatus("disable");
        int update = mapper.updateById(auth);
        return Result.success(200,"删除成功",update);
    }

    /**
     * 添加权限
     * @return
     */
    @Override
    public Result create(Auth auth) {
//        如果添加的权限为空
        if (auth.getName()==null){
            return Result.fail("添加失败");
        }else {
//            根据权限名字查找以及父id查找是否有相同的权限
            QueryWrapper<Auth> authQueryWrapper = new QueryWrapper<>();
            QueryWrapper<Auth> eq = authQueryWrapper
                    .eq("name", auth.getName())
                    .eq("pid", auth.getPid());
            Auth auth1 = mapper.selectOne(eq);
            if (auth1!=null){
//                如果有这个权限，添加失败
                return Result.fail("添加失败");
            }
            int insert = mapper.insert(auth);
            return Result.success(200,"添加成功",insert);
        }
    }

    /**
     * 修改权限
     * @param auth
     * @return
     */
    @Override
    public Result modify(Auth auth) {
        int update = mapper.updateById(auth);
        return Result.success(200,"修改成功",update);
    }


    /**
     * 根据id查看权限是否为父级，如果有，查询所有子级权限
     * @param id
     * @return
     */
    @Override
    public Result findChildren(Integer id) {
//        先查询是否为父级,根据此权限id查询所有pid=id的
        List<Auth> authChildren = mapper.query(id);
        return Result.success(200,"查询成功",authChildren);
    }
}
